import React, { useEffect, useState } from 'react';
import { Modal as AntdModal, Form, Input, Select, Radio, message } from 'antd';
import {
  getDepartmentStateList,
  checkDepartmentName,
  checkIsChildren,
  saveDepartment,
} from '@/services/departmentManage';

const Modal = ({
  modalVisible,
  modalTitle,
  updateModalVisible,
  modalData,
  departmentNameList,
  updateAid,
  Refresh,
}) => {
  const [form] = Form.useForm(); //用于显示表单数据
  const [stateList, setStateList] = useState([]);
  const [fatherAid, setFatherAid] = useState();
  const [stateId, setStateId] = useState(1);
  const [isSubmit1, setIsSubmit1] = useState(true);
  const [isSubmit2, setIsSubmit2] = useState(true);
  const layout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 18 },
  };

  //获取新增修改部门状态列表
  const getDepartmentStateListData = async () => {
    const msg = await getDepartmentStateList();
    setStateList(msg);
  };

  useEffect(() => {
    getDepartmentStateListData();
    if (modalVisible && modalData[0]) {
      form.setFieldsValue(modalData[0]);
      if (modalData[0].stateName === '启用') {
        setStateId(1);
      } else {
        setStateId(0);
      }
      if (departmentNameList) {
        departmentNameList.map((item) => {
          if (item.name === modalData[0].fatherDepartmentName) {
            setFatherAid(item.aid);
            return;
          }
        });
      }
    }

    if (modalTitle === '新增') {
      form.resetFields(); //清空表单
    }
  }, [modalVisible]);

  // 确定提交表单
  const actionHandle = () => {
    if (isSubmit1 && isSubmit2) {
      form.submit();
    } else if (!isSubmit1) {
      message.error('部门已存在！');
    } else if (!isSubmit2) {
      message.error('父部门为当前部门的部门的子孙部门！！');
    } else {
      message.error('部门已存在,父部门为当前部门的部门的子孙部门！！');
    }
  };

  //取消提交表单
  const handleCancel = () => {
    setIsSubmit1(true);
    setIsSubmit2(true);
    setFatherAid();
    setStateId(1);
    updateModalVisible();
  };

  // 获取表单数据，发送网络请求
  const onFinish = async (values) => {
    await saveDepartment({ name: values.name, fatherAid: fatherAid, id: stateId, aid: updateAid });
    setIsSubmit1(true);
    setIsSubmit2(true);
    setFatherAid();
    setStateId(1);
    Refresh();
    updateModalVisible();
  };

  //校验同名的其他部门
  const checkDepartment = async (name) => {
    const checkDepartmentList = await checkDepartmentName({ aid: updateAid, name });
    if (checkDepartmentList && checkDepartmentList.isExists) {
      form.setFieldsValue({
        ...checkDepartmentList.departmentInfoResult[0],
      });

      //保存同名部门的父部门aid
      departmentNameList.map((item) => {
        if (item.name === checkDepartmentList.departmentInfoResult[0].fatherDepartmentName) {
          setFatherAid(item.aid);
          return;
        }
      });
      setIsSubmit1(false);
      message.error('部门已存在！！');
    } else {
      setIsSubmit1(true);
    }
  };

  //检验父部门是否是其子孙分类
  const checkFatherDepartment = async () => {
    const checkFatherDepartmentList = await checkIsChildren({ aid: updateAid, fatherAid });
    if (checkFatherDepartmentList) {
      message.error('父部门不可为当前部门的子孙部门！');
      setIsSubmit2(false);
    } else {
      setIsSubmit2(true);
    }
  };

  const onChange = (value) => {
    setFatherAid(value);
  };

  const stateChange = (event) => {
    if (event.target.value === '启用') {
      setStateId(1);
    } else {
      setStateId(0);
    }
  };

  const allowClear = () => {
    setFatherAid();
    setIsSubmit2(true);
    return true;
  };

  return (
    <div>
      <AntdModal
        title={modalTitle}
        visible={modalVisible}
        onOk={actionHandle}
        onCancel={handleCancel}
        forceRender={true} //强制渲染modal
        maskClosable={false} //点击modal外面的界面不关闭
      >
        <Form
          {...layout}
          form={form}
          initialValues={{ stateName: '启用' }}
          onFinish={onFinish}
          validateTrigger="onBlur"
        >
          <Form.Item
            label="部门名称："
            name="name"
            rules={[
              {
                required: true,
                message: '部门名称为空',
              },
              {
                pattern: /^[\s\S]{1,16}$/,
                message: '部门名称格式错误！！',
              },
            ]}
            onBlur={(event) => {
              checkDepartment(event.target.value);
            }}
          >
            <Input placeholder="请输入" />
          </Form.Item>
          <Form.Item label="所属父部门:" name="fatherDepartmentName" onBlur={checkFatherDepartment}>
            <Select
              placeholder="请选择"
              onChange={onChange}
              allowClear={allowClear}
              showSearch
              filterOption={(input, option) =>
                option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
              }
            >
              {departmentNameList.map((item) => {
                return (
                  <Select.Option key={item.aid} value={item.aid}>
                    {item.name}
                  </Select.Option>
                );
              })}
            </Select>
          </Form.Item>
          <Form.Item label="状态" name="stateName" required="true">
            <Radio.Group onChange={stateChange}>
              {stateList.map((item) => {
                return (
                  <Radio key={item.id} value={item.name}>
                    {item.name}
                  </Radio>
                );
              })}
            </Radio.Group>
          </Form.Item>
        </Form>
      </AntdModal>
    </div>
  );
};

export default Modal;
